import { addNotice, getAllClass } from "../../utils/request/api";
import msg from "../../utils/msg";
import { formatTime,Throttle } from '../../utils/util';
import User from "../../utils/user";
var user = new User;
const throttle = Throttle();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    addContent: {
      title: '' as string,
      time: '' as string,
      people: user.name as string,
      content: '' as string,
      grade: '' as string,
      class: [] as string[],
      classes: '' as string,//传入后端的班级数据，各个班级之间以逗号分隔
    },
    columns: [
      {
        values: [] as Array<string>,
        className: 'column1',
      },
      {
        values: [] as Array<string>,
        className: 'column2',
        defaultIndex: 0,
      },
    ],
    show: false,
    showtime: false,
    minHour: 0,
    maxHour: 24,
    currentDate: new Date().getTime(),
    //数据格式如 {2021:[计科一班，计科二班]，2022:[网工一班，网工二班]}；
    AllClasses: {} as { [key: string]: Array<string> },
    grades: [] as string[],//前端显示的
    classes: [] as string[],//通过用户选择的年级显示对应班级
  },

  //提交
  submit: async function () {
    if(!this.checkData()) return;
    msg.Loading('正在发布');
    await throttle(2000)
    .then(async () => {
      await addNotice(this.data.addContent)
      .then(async () => { 
        msg.hideLoading();
        await msg.show('发布成功','');
        wx.navigateBack(); 
      })
      .catch(()=>{
        msg.show('发布失败','系统维护中');
      })
      msg.hideLoading();
    })
    .catch(() => {
      // 触发节流
      msg.show('请勿重复点击','');
    })
  },

  //检查数据不能为空
  checkData() {
    let addContent: any = this.data.addContent;
    for (let key of Object.keys(addContent)) {
      //console.log(key + ': ' + addContent[key]);
      if (!addContent[key]) {
        msg.show('有信息未填写', '请填写完整表单后再提交');
        return false;
      }
      if (key == 'class' && addContent[key].length == 0) {
        msg.show('至少要有一个班级', '');
      }
    };
    return true;
  },

  //获取输入
  getInput(e: any) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      ['addContent.' + index]: e.detail.value,
    });
  },

  //获取发布时间
  getInputTime(event: any) {
    let addContent = this.data.addContent;
    addContent.time = formatTime(new Date(event.detail));
    this.setData({
      addContent: addContent,
      showtime: false,
    });
  },

  //关闭弹窗
  onClose() {
    this.setData({
      show: false,
      showClass: false,
      showtime: false,
    })
  },

  //选择年级弹窗
  onChoose() {
    this.setData({
      show: true,
    })
  },
  //选择班级弹窗
  onChooseClass() {
    this.setData({
      showClass: true,
    })
  },

  //选择发布时间弹窗
  onChooseTime() {
    this.setData({
      showtime: true,
    })
  },

  //返回
  onClickLeft() {
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function () {
    let self = this;
    await getAllClass()
      .then((res: any) => {
        let classes: { [key: string]: Array<string> } = res.data.data;
        this.setData({
          AllClasses: classes,
          grades: Object.keys(classes),
        });
      });
  },

  gradeConfirm(event: any) {
    const { picker, value, index } = event.detail;
    let addContent = this.data.addContent;
    addContent.grade = value;
    addContent.class = this.data.AllClasses[value];
    let class_temp = '' as string;
    this.data.AllClasses[value].forEach((item) => {
      class_temp += item + ',';
    });
    this.data.addContent.classes = this.removeCommaEnd(class_temp);
    this.setData({
      addContent: addContent,
      classes: this.data.AllClasses[value],
      show: false,
    });
  },
  onChange(event: any) {
    let addContent = this.data.addContent;
    addContent.class = event.detail;
    let class_temp = '' as string;
    event.detail.forEach((item: any) => {
      class_temp += item + ',';
    });
    addContent.classes = this.removeCommaEnd(class_temp);
    this.setData({
      addContent: addContent,
    });
  },
  toggle(event: any) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  //去掉字符串末尾的逗号
  removeCommaEnd(input: string): string {
    let processedInput = input.trim(); // 去掉字符串前后的空格
    while (processedInput.endsWith(',')) {
      processedInput = processedInput.slice(0, -1); // 去掉字符串末尾的逗号
    }
    return processedInput;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})